package com.designpatterns.ProducerConsumer;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class ProducerConsumerBridgeNew {
    private  long MAX = 10;
    private  List<Resource> arraylist = new MyLinkedList<Resource>();
    private ReentrantLock lock = new ReentrantLock();
    private Condition notFull = lock.newCondition();
    private Condition notEmpty = lock.newCondition();

    public void produce() throws InterruptedException {
        lock.lock();
            System.out.println("\n\n");
            System.out.println("＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝");
            System.out.println("begin produce....");
            while (arraylist.size() >= MAX) {
                notFull.await();
            }
            arraylist.add(new Resource(Thread.currentThread().getName()));
            System.out.println("end produce now have:" + arraylist.toString());
            notEmpty.signalAll();
            System.out.println("＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝\n\n\n");
        lock.unlock();
    }

    public Resource consume() throws InterruptedException {
        lock.lock();
            System.out.println("\n\n");
            System.out.println("＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝");
            System.out.println("begin consume...");
            while (arraylist.size() <= 0) {
                notEmpty.await();
            }

            Resource resource = arraylist.remove(0);
            notFull.signalAll();
            System.out.println("end consume now have:" + arraylist.toString());
            System.out.println("＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝\n\n\n");
        lock.unlock();
        return resource;
    }
}
